#include "heroz_sound.hh"
#include <glob.h>
#include <algorithm>
#include <stdexcept>

std::vector<Mix_Music *> init_sound(const char *path) {
  int audio_rate;
  Uint16 audio_format;
  int audio_channels;
  int i;
  char **cptr;
  Mix_Music *muzak;
  std::vector<Mix_Music *> muzaks;
  glob_t globbuf;
  std::string globname(path);

  if(Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, AUDIO_S16, MIX_DEFAULT_CHANNELS, 1024) < 0)
    throw std::runtime_error(SDL_GetError());
#ifdef DEBUG
  Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels);
  printf("Opened audio at %d Hz %d bit %s\n", audio_rate,
         (audio_format & 0xFF), (audio_channels > 1) ? "stereo" : "mono");
#endif
  // Preload all the tunes into memory
  globname += "/mod.*";
  if((i = glob(globname.c_str(), 0, NULL, &globbuf)) != 0) {
    throw std::runtime_error(strerror(errno));
  }
  for(cptr = globbuf.gl_pathv; *cptr; ++cptr) {
    muzak = Mix_LoadMUS(*cptr);
#ifdef DEBUG
    printf("loading MOD '%s': %p\n", *cptr, muzak);
#endif
    if(!muzak) {
      throw std::runtime_error(SDL_GetError());
    } else {
      muzaks.push_back(muzak);
    }
  }
  globfree(&globbuf);
  return muzaks;
}

void cleanup_sound(std::vector<Mix_Music *> &muzaks) {
  std::for_each(muzaks.begin(), muzaks.end(), Mix_FreeMusic);
  muzaks.clear();
}
